package models

import (
	"database/sql"
	"fmt"
	"time"
)

type Class struct {
	ClassID     uint   `gorm:"primary_key"`
	ClassName   string `gorm:"unique_index;default:'whatclass'"` //班级名称
	InviteCode  string `gorm:"unique_index;default:'111111'"`    //班级邀请码
	ClassDescri string `gorm:"default:'暂时没有描述哦'"`                //班级描述
	TeacherID   uint   `gorm:"index;not null;"`                  //教师ID  外键 (属于), tag `index`是为该列创建索引 非空
	StudentNums int    `gorm:"default:0"`                        //学生人数
	ExamNums    int    `gorm:"default:0"`                        //测试数
	NoticeNum   int    `gorm:"default:0"`                        //公告数

	Project    string   `gorm:"-"` //班级科目 数据库忽略这个字段
	ClassLogo  string   //班级logo
	ClassColor string   //班级color
	Notices    []Notice `gorm:"many2many:class_notice;"` // Many-To-Many , 'class_notice'是连接表
	CreatedAt  time.Time
	UpdatedAt  time.Time
}

// insert class
func (c *Class) Insert() error {
	return DB.Create(c).Error
}

//get the last class id
func (c *Class) GetLastClassID() (error error, id uint) {
	var classtem Class
	err := DB.Last(&classtem).Error
	return err, classtem.ClassID
}

//update  class  by classid
func (c *Class) UpdateClass() error {
	var err error
	err = DB.Model(c).Updates(
		map[string]interface{}{"class_name": c.ClassName,
			"class_descri": c.ClassDescri, "invite_code": c.InviteCode}).Error
	//err = DB.Where("class_id = ?", c.ClassID).Find(&classtem).Error
	return err
}

//根据管理员 也就是教师查找所有班级
func ListAllClass(teacherid uint) ([]*Class, error) {
	var classes []*Class
	var err error

	err = DB.Where("teacher_id = ?", teacherid).Find(&classes).Error
	return classes, err
}

func (c *Class) DeleteClass() error {
	return DB.Delete(c).Error
}

//Notice是绑定班级发布 所以删除班级的时候也要删除这个班级所有的Notice
//

func (c *Class) DeleteRelated() error {
	var err error
	var notices []Notice
	var rows *sql.Rows
	var rows2 *sql.Rows
	var exams []*Exam
	var total int
	//业务 将发布的测试 根据具体情况 置为未发布 如果删除完exam_class这个班级的记录之后 还能查询到这个examid 则不置为 否则置为
	//先根据删除的班级id 查询到所有的这个班级发布的测试
	//然后根据找到的测试 查询exams表
	rows, err = DB.Raw("select * from exams  where exam_id in (select exam_exam_id from exam_class where class_class_id IN (?)) ", c.ClassID).Rows()
	if err != nil {
		return err
	}
	defer rows.Close()
	for rows.Next() {
		var exam Exam
		DB.ScanRows(rows, &exam)
		exams = append(exams, &exam)
	}
	err = DB.Exec("DELETE FROM exam_class WHERE  class_class_id IN (?)", c.ClassID).Error
	for _, val := range exams {
		rows2, err = DB.Raw("select count(*) as total from exam_class where exam_exam_id IN (?)  ", val.ExamID).Rows()
		if err != nil {
			return err
		}
		col, _ := rows2.Columns()
		fmt.Println(col[0])

		defer rows2.Close()
		for rows2.Next() {
			rows2.Scan(&total)
		}

		//还能查询到这个examid 则不置为未发布
		if total > 0 {

		} else {
			err = DB.Exec("UPDATE exams SET is_published=false WHERE exam_id IN (?)", uint(val.ExamID)).Error
		}

	}

	err = DB.Exec("DELETE FROM stu_class WHERE  class_class_id IN (?)", c.ClassID).Error
	err = DB.Exec("DELETE FROM class_notice WHERE  class_class_id IN (?)", c.ClassID).Error
	DB.Model(&c).Related(&notices, "Notices")
	for _, val := range notices {
		var noticeid = val.NoticeID
		err = DB.Exec("DELETE FROM notices WHERE  notice_id IN (?)", uint(noticeid)).Error
	}
	return err
}
